#include "../include/SocketHelp.hpp"
#include <thread>
#define BUF_SIZE 1024

void WriteThread(int sockfd)
{
    char* message;
    size_t len;
    ssize_t readLine;
    while((readLine = getline(&message,&len,stdin))!=-1)
    {
        if(strcmp("Quit\n",message)==0)
        {
            break;
        }
        send(sockfd,message,readLine-1,0);
    }
    return;
}

void ReadThread(int sockfd)
{
    int length = -1;
    char buffer[BUF_SIZE];
    memset(buffer,'\0',BUF_SIZE);
    while((length = recv(sockfd,buffer,BUF_SIZE-1,0))!=-1)
    {
       printf("Got Message For Other Client %s\n",buffer);
    }
    return;
}

int main(int argc,char** argv)
{
    if(argc <= 2)
    {
        printf("Usgae:%s ip_address port_number\n",basename(argv[0]));
        return -1;
    }
    const char* ip = argv[1];
    int port = atoi(argv[2]);

    struct sockaddr_in server_address;
    bzero(&server_address,sizeof(server_address));
    server_address.sin_family = AF_INET;
    inet_pton(AF_INET,ip,&server_address.sin_addr);
    server_address.sin_port = port;

    int sockfd = socket(PF_INET,SOCK_STREAM,0);
    assert(sockfd >= 0);

    if(connect(sockfd,(struct sockaddr*)&server_address,sizeof(server_address))<0)
    {
        printf("Connect Error !\n");
    }else
    {
        std::thread writeThread(WriteThread,sockfd);
        std::thread readThread(ReadThread,sockfd);
        writeThread.join();
        readThread.join();
    }
    close(sockfd);
    return 0;
}
